package com.xuanyuanxinyu.func.network.retrofit

import android.net.Uri
import com.alibaba.fastjson.JSON
import com.google.gson.JsonObject
import com.xuanyuanxinyu.func.network.internal.MediaTypeConstant
import com.xuanyuanxinyu.utils.log.AppLog
import com.xuanyuanxinyu.utils.log.AppLog.logE

import okhttp3.MediaType
import okhttp3.Request
import okhttp3.RequestBody
import okhttp3.Response
import okhttp3.ResponseBody
import okio.Buffer
import java.io.IOException
import java.net.URLDecoder
import java.nio.charset.Charset
import java.nio.charset.StandardCharsets

/**
 * @FileName:
 * @Description:
 * @author ken.luo
 * @date 2023/4/4
 * @version V1.0
 * @email 424533553@qq.com
 */
object RetrofitUtils {

    /**
     * 获取Request 信息
     */
    private fun getRequestContent(request : Request) {
        // 请求URL
        val url = request.url.toString()
        // 请求的方法GET或POST
        val method = request.method
        // 请求的header
        val headers = request.headers
        val headerStr = if (headers.size > 0) JSON.toJSONString(headers.toMultimap()) else ""
        val requestBody = request.body
        if (requestBody != null) {
            // media类型
            val mediaType = requestBody.contentType()
        }
    }

    /**
     * 获取请求后，返回的内容
     *
     */
    private fun getResponseContent(response : Response) {
        try {
            //读取服务器返回的结果
            val responseBody = response.body
            val source = responseBody!!.source()
            source.request(Long.MAX_VALUE) // Buffer the entire body.
            val buffer = source.buffer()
            //获取content的压缩类型
            val encoding = response.headers["Content-Encoding"]
            //克隆服务器的响应内容()
            val cloneBuffer = buffer.clone()
        } catch (e : IOException) {
            logE(RetrofitUtils::class.java, AppLog.GROUP_RETROFIT, "解析返回内容失败")
        }
    }

    /**
     * 获取GET请求中的参数
     */
    private fun getRequestParams4Get(url : String) : String {
        val uri = Uri.parse(url)
        val requestJson = JsonObject()
        for (paramKey in uri.queryParameterNames) {
            val paramValue = uri.getQueryParameter(paramKey)
            requestJson.addProperty(paramKey, paramValue)
        }
        return requestJson.toString()
    }

    /**
     * 解析请求服务器的POST请求参数解析出来
     */
    private fun parseRequestParams4Post(request : Request) {
        try {
            val body = request.body ?: return
            val requestBuffer = Buffer()
            body.writeTo(requestBuffer)
            var charset = StandardCharsets.UTF_8
            val contentType = body.contentType()

            if (contentType != null) {
                charset = contentType.charset(charset)
            }
            var text : String? = requestBuffer.readString(charset!!)

            if (contentType != null && "json" != contentType.subtype) {
                text = URLDecoder.decode(text, convertCharset(charset))
            }
            // 将请求参数转换为Json数据
        } catch (e : IOException) {
            e.printStackTrace()
        }
    }

    private fun convertCharset(charset : Charset?) : String {
        val s = charset.toString()
        val i = s.indexOf("[")
        if (i == -1) {
            return s
        }
        return s.substring(i + 1, s.length - 1)
    }

    /**
     * 是否文本类型
     */
    fun isText(mediaType : MediaType) : Boolean {
        if (MediaTypeConstant.TEXT == mediaType.type) {
            return true
        }
        return MediaTypeConstant.JSON == mediaType.subtype
                || MediaTypeConstant.XML == mediaType.subtype
                || MediaTypeConstant.HTM == mediaType.subtype
                || MediaTypeConstant.HTML == mediaType.subtype
                || MediaTypeConstant.WEBVIEWHTML == mediaType.subtype
    }

    /**
     * 将Body中的内容转成String
     */
    fun bodyToString(request : Request) : String {
        val copy = request.newBuilder().build()
        val buffer = Buffer()
        try {
            if (copy.body != null) {
                copy.body!!.writeTo(buffer)
            }
        } catch (e : Exception) {
            return "occurs error when show requestBody"
        }
        return buffer.readUtf8()
    }

    /**
     * 将RequestBody中内容转成String
     */
    fun bodyToString(request : RequestBody?) : String? {
        if (request != null) {
            try {
                val copy : RequestBody = request
                val buffer = Buffer()
                copy.writeTo(buffer)
                return buffer.readUtf8()
            } catch (e : IOException) {
                logE(RetrofitUtils::class.java, AppLog.GROUP_RETROFIT, e.toString() + "Did not work.")
            }
        }
        return null
    }

    /**
     * 创建新的Response、更改其中的配置参数
     */
    fun createResponse(response : Response) : Response {
        val mediaType = response.body!!.contentType()
        val responseData = response.body!!.bytes()
        return response.newBuilder()
                .headers(response.headers)
                .body(ResponseBody.create(mediaType, responseData))
                .build()
    }

}